const knex = require("../../db/knex");
const {wuyuan, jingdainyu} = require("../../utils/wuyuan");
const wuyuan5 = require("../../utils/wuyuan5");

// const {log} = require("debug");/


async function submitAnalysis(params, res) {

    async function get_wuyuanParam_and_count_Result(questionnaire_id) {
        let fullMark1 = await countQuestionFullMark(questionnaire_id)//得到该问卷,知情意行四方面分别满分分数用于构建经典域
        let jd = fullMark1.map(o => {
            return jingdainyu(o)
        })// 构建经典域
        let result = await getSubmittedScore(questionnaire_id)//获取所有指定问卷id的已提交的问卷的得分情况
        const level = wuyuan5(jd, result)
        console.log(result, '看结果', level, '京东', fullMark1)
        return level
    }

    async function getResultFn(questionnaire_id) {
        let fullMark1 = await countQuestionFullMark(questionnaire_id)//得到该问卷,知情意行四方面分别满分分数
        let scoreResult = await getSubmittedScore(questionnaire_id)//获取所有指定问卷id的已提交的问卷的得分情况
        let level = []

        function addInnerArray(arr) {
            const result = [];
            // 遍历外层数组
            for (let i = 0; i < arr.length; i++) {
                // 遍历内层数组
                for (let j = 0; j < arr[i].length; j++) {
                    // 判断是否已经存在当前位置的结果
                    if (!result[j]) {
                        result[j] = 0;
                    }
                    // 将内层数组对应位置的元素相加
                    result[j] += arr[i][j];
                }
            }
            return result;
        }

        let precentArr = []
        let result = addInnerArray(scoreResult)
        console.log(result, fullMark1)
        for (let i = 0; i < result.length; i++) {
            let countRes = result[i] / scoreResult.length / fullMark1[i]
            console.log(countRes, 'smsdauh')
            precentArr.push(countRes)
        }
        // console.log(precentArr, '统计')
        for (let i = 0; i < precentArr.length; i++) {
            if (precentArr[i] < 0.55) {
                level[i] = '差'
            } else if (0.55 < precentArr[i] <= 0.7) {
                level[i] = '中'
            } else if (0.7 < precentArr[i] <= 0.85) {
                level[i] = '良'
            } else if (0.85 < precentArr[i] <= 1) {
                level[i] = '优'
            }
            // console.log(precentArr, '急眼')
        }
        return level
    }

    let before_Result = await getResultFn(params.Questionnaire_before)
    let after_Result = await getResultFn(params.Questionnaire_after)
    // console.log(res77, '4845', res88)
    // let before_Result = await get_wuyuanParam_and_count_Result(params.Questionnaire_before)
    // let after_Result = await get_wuyuanParam_and_count_Result(params.Questionnaire_after)
    let levelchange = ''
    for (let i = 0; i < 4; i++) {
        levelchange += `${before_Result[i]}-${after_Result[i]} `
    }
    let info = {
        analysis_title: params.analysis_title,
        create_time: params.create_time,
        questionnaire_before: params.Questionnaire_before,
        questionnaire_after: params.Questionnaire_after,
        class: params.class,
        change: levelchange
    }
    await knex.transaction(async trx => {
        let {title: title1} = await trx('save_questionnaire').select('title').where({id: params.Questionnaire_before}).first()
        let {title: title2} = await trx('save_questionnaire').select('title').where({id: params.Questionnaire_after}).first()
        console.log(title1, 'title')
        info.questionnaire_title = `${title1}--${title2}`
        await trx('analysis_result').insert(info)
        res.send({
            msg: "成功"
        })
    })

}

async function handleAnalysis(before, after) {//接收学前问卷id,学后问卷id,根据id获取每一份已填写问卷获得的分数
    //1.先获取学前问卷和学后问卷
    let beforeData
    let afterData
    await knex.transaction(async trx => {
        afterData =
            await trx('answer_list').select('uid', 'questionnaire_id')
                .where({questionnaire_id: after})
                .groupBy('uid')
                .sum('total_score as sum_total_score');
        afterData = afterData.map(o => {
            return o.sum_total_score
            // uid: o.uid,
            // questionnaire_id: o.questionnaire_id,
        })
        beforeData =
            await trx('answer_list').select('uid', 'questionnaire_id')
                .where({questionnaire_id: before})
                .groupBy('uid')
                .sum('total_score as sum_total_score');
        beforeData = beforeData.map(o => {
            return o.sum_total_score
            // uid: o.uid,
            // questionnaire_id: o.questionnaire_id,
        })
    })

    return {
        beforeData,
        afterData
    }
}

//count
async function countQuestionFullMark(questionnaire_id) {   //计算一个问题的满分
                                                           //1.首先应该判断问题是多选还是单选,根据问卷id,查询该问卷对应标签问题id
    let fullMark = []//有四个元素,分别表示知,情,意,行四个标签题目的满分
    fullMark[0] = 0
    await knex.transaction(async trx => {
        //1.1先获取知,情,意,行标签单选题(四个标签对应的数字分别为1,2,3,4)
        for (let i = 1; i < 5; i++) {
            let arr1, arr2 = []
            let query1 = await trx('question_list').select('question_id').where({label: i}).andWhere('type', '单选')
                .andWhere('questionnaire_id', questionnaire_id)
            arr1 = query1.map(o => {
                return o.question_id
            })
            //1.2知标签多选题
            let query2 = await trx('question_list').select('question_id').where({label: i}).andWhere('type', '多选')
                .andWhere('questionnaire_id', questionnaire_id)
            arr2 = query2.map(o => {
                return o.question_id
            })
            fullMark[i] = 0
            console.log(arr1, 'arr1', i, questionnaire_id)
            //对于单选题,哪一项分值最大,满分就是该分值
            for (const o of Array.from(arr1)) {
                if (!o) {
                    continue
                }
                // let i = arr1.indexOf(o)
                let query3 = await trx('option_list')
                    .where({question_id: o}).andWhere({questionnaire_id: questionnaire_id}).max('score as max_score')
                query3 = query3[0].max_score
                console.log(query3, 'query3')
                fullMark[i] += query3 ?? 0
            }
            // console.log('去去去去去去去去去', fullMark, '猜猜看')
            //多选题,该题满分就是所有选项的和
            for (const o of Array.from(arr2)) {
                // const i = Array.from(arr2).indexOf(o);
                let rows = await trx('option_list')
                    .where({
                        question_id: o
                    }).andWhere({questionnaire_id: questionnaire_id})
                    .sum('score as totals')
                // console.log('************', rows, '行')
                fullMark[i] += rows[0].totals ?? 0
            }
            // console.log(fullMark, '什么')
        }


    })
    fullMark.splice(0, 1)
    return fullMark
}

async function getSubmittedScore(questionnaire_id) {
    let arr = []
    arr[0] = 0
    let arr2 = []
    arr2[0] = []
    let uidCount
    await knex.transaction(async trx => {
        let QQ = (await trx('answer_list').select('uid').where({questionnaire_id: questionnaire_id}).distinct()).length//根据uid查询有多少份已提交问卷

        for (let i = 1; i < 5; i++) {//四种标签
            let query1 = await trx('question_list').select('question_id').where({label: i})
                .andWhere('questionnaire_id', questionnaire_id)
            let query = query1.map(o => o.question_id)
            arr[i] = 0;
            // console.log('query1',query)
            // for (const o of query) {
            //     let query2 = await trx('answer_list').where({question_id: o}).andWhere('questionnaire_id', questionnaire_id)
            //         .sum('total_score as total').groupBy('uid')
            //     console.log('query2', query2, '---------')
            //     arr[i] += query2[0].total
            // }
            arr2[i] = []
            // arr2[]
            let arr3 = []
            // console.log(arr[i], '康康二体', query)
            for (const o of query) {
                arr3 = (await trx('answer_list').where({question_id: o}).andWhere('questionnaire_id', questionnaire_id)
                    .sum('total_score as total').groupBy('uid')).map(o => {
                    return o.total
                })

            }
            // console.log(arr3, '3333333333')
            arr3.forEach((o, ia) => {
                arr2[ia][0] = 0
                arr2[ia][i] = o
            })

        }
        arr2.splice(QQ, arr2.length - 1)//去掉第一维的空数组
        arr2.forEach(o => {//去除第二维的第一个0
            o.splice(0, 1)
        })
    })
    console.log(arr2, '康康arr2的样子')
    return arr2
}

async function getAnalysisResult(res) {
    await knex.transaction(async trx => {
        let result = await trx('analysis_result').select('*')
        res.status(200).send({
            result
        })
    })
}

async function deleteAnalysisResult(param, res) {
    console.log(param)
    await knex.transaction(async trx => {
        await trx('analysis_result').del().where({id: param.id})
    })
    res.send({
        msg: "成功"
    })
}

module.exports = {
    submitAnalysis,
    getAnalysisResult,
    deleteAnalysisResult
}
